const express = require("express")
const app = express()
const bodyParser = require("body-parser");
const Json = require("json-schema")

//解决跨域问题
//app.use(require("cors")());

/*修改服务端代码，进行全路由配置，允许跨域请求*/
app.all('*', function (req, res, next) {
  res.header('Access-Control-Allow-Origin', '*');
  res.header('Access-Control-Allow-Headers', 'Content-Type, Content-Length, Authorization, Accept, X-Requested-With, yourHeaderFeild');
  res.header('Access-Control-Allow-Methods', 'PUT, POST, GET, DELETE, OPTIONS');
  res.header("Content-Type", "text/plain; charset=utf-8")

  if (req.method === 'OPTIONS') {
    res.send(200);
  }
  else {
    next();
  }
});

// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }));

// parse application/json
app.use(bodyParser.json());

var tallyRouter = require('./db/tally');
var deletetallyRouter = require('./db/deletetally');
var addRouter = require('./db/addtally');
app.use('/tally', tallyRouter);
app.use('/delete/tally', deletetallyRouter);
app.use('/add/tally', addRouter);


// const mongoose = require("mongoose");
// mongoose.connect('mongodb://localhost/tally', {//连接数据库
//   useNewUrlParser: true,
// }, (err) => {
//   if (err) {
//     return console.log(err);
//   }
//   console.log("数据库连接成功!");
// });

// const Schema = mongoose.Schema;
// const TallySchema = new Schema({
//   createdTime: {
//     type: Date,
//     require: true
//   }, type: {
//     type: Number,
//     require: true
//   }, price: {
//     type: String,
//     require: true
//   }, remark: {
//     type: String,
//     require: true
//   }, tag: {
//     type: String,
//     require: true
//   },

// });
// const Tally = mongoose.model("Tally", TallySchema, "tallies");
// Tally.create(
//     { createdTime: 1610979686949, type: 0, price: "800", remark: "一日三餐共30天", tag: "吃饭" },
//     { createdTime: 1610979007310, type: 1, price: "2000", remark: "每月生活费", tag: "生活费" }
// )
app.get("/gettallydata", async (req, res) => {
  const gtd = await Tally.find({});
  res.send(gtd);
})

app.listen(8888, () => {
  console.log("server is running at http://127.0.0.1:8888");
});